<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExportExcel">excel导出</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="EmployeesList" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" width="50px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formOfEmployeesFormat(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template #default="{row}">
              {{ timeMate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRoles(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <add-or-edit
          v-if="showDialog"
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>
      <!-- 分配角色弹框 -->
      <el-dialog
        v-if="showRoleDialog"
        title="分配角色"
        :visible.sync="showRoleDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <AssignRole
          ref="assignRole"
          :cur-id="curId"
          @success="hRoleSuccess"
          @close="showRoleDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import addOrEdit from './empDialog.vue'
import AssignRole from './assignRole.vue'
// console.log('EmployeesEnum', EmployeesEnum.hireType)
// [{id: 2, value: '非正式'},{id: 1, value: '正式'}]
// const hireType = {}
// // {1: '正式', 2: '非正式'}
// // 映射数组 形成新对象 优化代码
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log(hireType, 'hireType')
export default {
  components: {
    addOrEdit, AssignRole
  },
  data() {
    return {
      // 分配角色id
      curId: '',
      showRoleDialog: false,
      showDialog: false,
      page: 1,
      size: 5,
      total: 0,
      // 员工列表数据
      EmployeesList: []
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    // 子向父自定义事件
    hRoleSuccess() {
      // 关闭弹层
      this.showRoleDialog = false
      // 刷新页面
      this.loadEmployeesList()
    },
    // 分配角色按钮
    hAssignRoles(id) {
      this.showRoleDialog = true
      this.curId = id
    },
    // 子向自定义事件
    hSuccess() {
      this.showDialog = false
      // 优化新增页数bug
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeesList()
    },
    // 删除接口
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        this.$message.success(res.message)
        // 优化删除
        if (this.EmployeesList.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeesList()
      } catch (error) {
        console.log(error)
      }
    },
    // 实现删除
    hDel(id) {
      this.$confirm('此操作将永久删除该员工信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },
    // 转换数据
    formOfEmployeesFormat(num) {
    // // 通过find方法找到对应的对象
    // const item = EmployeesEnum.hireType.find(item => item.id === num)
    // // 如果返回的是1或者2 则返回value
    // if (item) {
    //   return item.value
    // } else {
    //   // 其他数字则是 未知
    //   return '未知'
    // }
      return hireType[num]
    },
    timeMate(time) {
      return time.split('T')[0]
    },
    // 获取员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log(res, '获取员工列表')
        this.EmployeesList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 格式化导出数据
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 表格头部的数据
      let header = []
      // 那表格内容数组
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      // 将英文的头部内容转换为中文
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] || '未知'// hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    // 导出excel
    async hExportExcel() {
      // 1发送请求获取数据
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log('excel', res)
        const list = res.data.rows
        // console.log(list)
        const { header, data } = this.formatData(list)
        console.log('header', header) // 表格头部数据
        console.log('data', data) // 表格内容数据
        // 2 数据格式化到需要的格式
        // 3 导出excel表格
        import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
            header: header, // 表头 必填
            data: data, // 具体数据 必填
            filename: 'excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
